import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jyofservice/bean/xiafa_person_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/generated/json/base/json_convert_content.dart';
import 'package:jyofservice/util/EncodeUtil.dart';
import 'package:jyofservice/util/Image_picked.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/bean/charge_data_entity.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:jyofservice/bean/diaodu_detail_entity.dart';
import 'package:jyofservice/util/SlideRoute.dart';
import 'package:jyofservice/gongdandiaodu/HistroyMenu.dart';
import 'package:jyofservice/gongdandiaodu/CommonUnit.dart';
import 'package:jyofservice/gongdandiaodu/WorkRecord.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:uuid/uuid.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../util/AssetPicker.dart';

class CheckDetail extends StatefulWidget {
  String? LSH;
  bool? is0ffstage;
  String? view;
  //是否转交和确认工单
  bool? isDeliver;
  //是否接单超时 是和否
  String? isjdyq;
  //接单时限
  String? jdsxTime;
  CheckDetail(
      {this.LSH,
      this.is0ffstage,
      this.view,
      this.isDeliver,
      this.isjdyq,
      this.jdsxTime});

  @override
  _CheckDetailState createState() => _CheckDetailState();
}

class _CheckDetailState extends State<CheckDetail> {
  DiaoduDetailDataData? detailEntity = new DiaoduDetailDataData();
  late SharedPreferences sharedPreferences;
  TextEditingController ideaController = TextEditingController();
  TextEditingController deliverController = TextEditingController();
  ChargeDataDataData? sfInfoEntity;
  String? detailStr;
  String? key;
  bool isloading = false;

  List<XiafaPersonData> personLists = [];
  late XiafaPersonEntity personEntity;
  String ss = '已缴费';

  //记录从相册选择的附件图片
  List<String> _imageUrlsEdit = [];
  String _path = '';
  List fileArrs = [];

  List<AssetEntity> assets = <AssetEntity>[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getPath();
    getDetailData().then((value) {
      getSFData();
      getFeeState();
    });

  }

  //获得应用文档目录
  Future _getPath() async {
    sharedPreferences = await SharedPreferences.getInstance();
    final Directory _directory = await getApplicationDocumentsDirectory();
    final Directory _imageDirectory =
    await new Directory('${_directory.path}/image/')
        .create(recursive: true);
    _path = _imageDirectory.path;
    print('本次获得路径：${_imageDirectory.path}');
    return _path;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('工单详情',
            style: TextStyle(
                color: Colors.white, fontSize: ScreenUtil().setSp(45))),
        actions: <Widget>[
          PopupMenuButton<String>(
            icon: Icon(Icons.more_horiz),
            offset: Offset(0, 20),
            itemBuilder: (BuildContext context) {
              return <PopupMenuItem<String>>[
                this.SelectView('历史工单', 'B'),
                this.SelectView('同单元工单', 'C'),
                this.SelectView('工单日志', 'D'),
              ];
            },
            onSelected: (String action) {
              // 点击选项的时候
              switch (action) {
                case 'B':
                  Navigator.of(context).push(SlideRoute().createRoute(
                      HistroyPage(
                          sfbm: detailEntity!.sfbm,
                          xqid: detailEntity!.allName)));
                  break;
                case 'C':
                  Navigator.of(context).push(SlideRoute().createRoute(
                      CommonUnitPage(
                          sfbm: detailEntity!.sfbm, xqid: detailEntity!.xqId)));
                  break;
                case 'D':
                  Navigator.of(context).push(
                      SlideRoute().createRoute(WorkRecord(LSH: widget.LSH)));
                  break;
              }
            },
          ),
        ],
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Stack(
              alignment: Alignment(0.5, 0.5),
              children: <Widget>[
                SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      Container(
                        color: Colors.blue,
                        width: ScreenUtil().screenWidth,
                        height: ScreenUtil().setHeight(100),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            SizedBox(
                              width: ScreenUtil().setWidth(30),
                            ),
                            Expanded(
                                child: Container(
                              child: Text(
                                detailEntity!.describe ?? '',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(40)),
                              ),
                            )),
                            Expanded(
                              flex: 1,
                              child: SizedBox(),
                            ),
                            Icon(
                              Icons.access_time,
                              color: Colors.white,
                            ),
                            Text(detailEntity!.stateName ?? '',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(40))),
                            SizedBox(
                              width: ScreenUtil().setWidth(30),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.person,
                              color: Colors.blue,
                            ),
                            Text(
                              '用户信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                            Expanded(
                              child: Container(),
                            ),
                            Offstage(
                              offstage: widget.view == "GetMySelfWaitDoWork"
                                  ? false
                                  : true,
                              child: Padding(
                                padding: EdgeInsets.all(5),
                                child: Text(
                                  detailEntity!.isRead == 1 ? "[已读]" : "[未读]",
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(32),
                                      color: detailEntity!.isRead == 1
                                          ? Colors.green
                                          : Colors.red),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      getRow("联系人", detailEntity!.linkMan),
                      getPhoneRow("联系电话", detailEntity!.comePhone),
                      getRow("住户地址", detailEntity!.allName),
                      getRow("住户备注", detailEntity!.zHRemarks),
                      getRow("住户编码", detailEntity!.sfbm),
                      getRow("交费状态", ss),
                      getRow("是否VIP", getGNstate()),
                      getRow("天气状况", detailEntity!.weather),
                      getRow("控制信息", detailEntity!.azfsName),
                      Container(
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        color: Colors.grey,
                        height: ScreenUtil().setHeight(2),
                        width: ScreenUtil().screenWidth,
                      ),
                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.filter,
                              color: Colors.blue,
                            ),
                            Text(
                              '工单信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                          ],
                        ),
                      ),
                      getRow("工单描述", detailEntity!.describe),
                      getRow("工单来源", detailEntity!.fromTypeName),
                      getPhoneRow("来电号码", detailEntity!.comePhone),
                      getRow("工单区域", detailEntity!.regionName),
                      getRow("工单类型", detailEntity!.typeName),
                      getRow("工单状态", detailEntity!.stateName),

                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.add_to_photos,
                              color: Colors.blue,
                            ),
                            Text(
                              '下单信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                          ],
                        ),
                      ),
                      getRow("下单时间", detailEntity!.createDate),
                      // getRow("下单人员", detailEntity.createUserName),
                      getRow("修改时间", detailEntity!.updateDate ?? ''),
                      getRow("处理时限", detailEntity!.limitTime.toString() + "小时"),
                      getRow("是否退回", detailEntity!.hBName),
                      getRow("是否超时", detailEntity!.ifyq),
                      getRow("紧急程度", detailEntity!.importName),
                      Container(
                        height: ScreenUtil().setHeight(70),
                        padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(
                              Icons.assistant_photo,
                              color: Colors.blue,
                            ),
                            Text(
                              '接单信息',
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenUtil().setSp(40)),
                            ),
                          ],
                        ),
                      ),
                      getRow(
                          "接单时限",
                          widget.jdsxTime == null
                              ? ""
                              : widget.jdsxTime! + "小时"),
                      getRow("接单时间", detailEntity!.confirmTime),
                      getRow("是否超时", widget.isjdyq),
                      SizedBox(
                          height: 10.0,
                          child: Container(
                            color: Colors.black12,
                          )),
                      //添加图片视图
                      JhAssetPicker(
                        assetType: AssetTypes.image,
                        lineCount: 3,
                        callBack:
                            (assetEntityList, CallBackType type) {
                          if (type == CallBackType.add) {
                            Navigator.pop(context);
                          }
                          print('assetEntityList-------------');
                          print(assetEntityList);
                          print('assetEntityList-------------');

                          assets = assetEntityList;
                          if (mounted) {
                            setState(() {});
                          }
                        },
                      ),
                    ],
                  ),
                ),
                Offstage(
                  offstage: isloading,
                  child: SpinKitFadingCircle(
                    color: Colors.blue,
                    size: 50.0,
                  ),
                )
              ],
            ),
          ),
          typeBtnView()
        ],
      ),
    );
  }

  Widget typeBtnView() {
    return widget.isDeliver!
        ? GestureDetector( //工单转交
            onTap: () {
              getPersonData().then((value) {
                showMyDialog();
              });
            },
            child: Container(
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.white), color: Colors.blue),
              height: ScreenUtil().setHeight(100),
              width: ScreenUtil().screenWidth,
              child: Center(
                child: Text(
                  '转交工单',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ))
        : Row(
            //确认与退回工单
            children: [
              Expanded(
                  child: GestureDetector(
                onTap: () {
                  showAlertGD();
                },
                child: Container(
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.white),
                      color: Colors.blue),
                  height: ScreenUtil().setHeight(100),
                  width: ScreenUtil().screenWidth,
                  child: Center(
                    child: Text(
                      '确认工单',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              )),
              Expanded(
                  child: GestureDetector(
                onTap: () {
                  showAlertBack();
                },
                child: Container(
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.blue),
                      color: Colors.blue),
                  height: ScreenUtil().setHeight(100),
                  width: ScreenUtil().screenWidth,
                  child: Center(
                    child: Text(
                      '退回工单',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ))
            ],
          );
  }

  Widget getRow(String str1, String? str2) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SelectableText(
            str1 ?? '',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
            flex: 1,
            child: SelectableText(
              str2 ?? '',
              style: TextStyle(
                  color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
            ),
          ),
        ],
      ),
    );
  }

  Widget getPhoneRow(String str1, String? str2) {
    return Container(
      padding: EdgeInsets.only(left: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          SelectableText(
            str1 ?? '',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
              flex: 1,
              child: GestureDetector(
                child: Container(
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: SelectableText(
                            str2 ?? '',
                            style: TextStyle(
                                color: Colors.black87,
                                fontSize: ScreenUtil().setSp(35)),
                          ),
                        ),
                        Offstage(
                          offstage: str2 != "" ? false : true,
                          child: TextButton.icon(
                              onPressed: () {
                                _launchPhone(str2);
                              },
                              icon: Icon(
                                Icons.phone_in_talk,
                                size: ScreenUtil().setSp(38),
                              ),
                              label: Text(
                                "呼叫",
                                style:
                                    TextStyle(fontSize: ScreenUtil().setSp(28)),
                              )),
                        )
                      ],
                    )),
                onTap: () {
                  _launchPhone(str2);
                },
              )),
        ],
      ),
    );
  }

  String? getGNstate() {
    String str = "";

    if (sfInfoEntity == null) {
      return str;
    } else {
      return sfInfoEntity!.isvip;
    }
  }

  _launchPhone(str) async {
    if (str != "" && str != null) {
      var url = 'tel:$str';
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        Fluttertoast.showToast(msg: "号码有误,不能拨打电话");
        throw 'Could not launch $url';
      }
    } else {
      Fluttertoast.showToast(msg: "号码有误,不能拨打电话");
    }
  }

  //获取详情
  Future getDetailData() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");

    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "view": "vw_GD_main",
      "wherestr": "LSH='" + widget.LSH! + "'",
      "sortName": "ID",
      "sortOrder": "asc",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());
    Response response = await Dio()
        .post(WebConfig().baseUrl + "DB/getrowdatanopage", data: data);
    print("获取详情：" + response.data.toString());
    isloading = true;
    if (mounted) {
      setState(() {
        if (response.data["Code"] == "200") {
          detailEntity =
              JsonConvert.fromJsonAsT(response.data["Data"]["data"][0]);
        }
      });
    }

    return response.data;
  }

  //获取住户收费信息
  Future getSFData() async {
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "vw_Public_House",
      "wherestr": "House_id='" + detailEntity!.houseId.toString() + "'",
      "sortName": "Xq_name",
      "sortOrder": "asc",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio()
        .post(WebConfig().baseUrl + "DB/getrowdatanopage", data: data);
    print("收费===$data" + response.data.toString());
    if (mounted) {
      setState(() {
        if (response.data["Code"] == "200") {
          if (response.data["Data"]["data"].length > 0) {
            sfInfoEntity = new ChargeDataDataData.fromJson(
                response.data["Data"]["data"][0]);
          }
        }
      });
    }
    return response.data;
  }

  //获取交费状态
  Future getFeeState() async {
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "vw_Public_House",
      "wherestr": "House_id='" + detailEntity!.houseId.toString() + "'",
      "sortName": "Xq_name",
      "sortOrder": "asc",
      "ClientType": "phone",
      "ClientKey": aesData,
      "sfbm": detailEntity!.sfbm
    };
    Response response = await Dio()
        .post(WebConfig().baseUrl + "DB/getFeeYearPayInfo", data: data);
    print("收费数据" + response.data.toString());
    if (mounted) {
      setState(() {
        if (response.data["Code"] == "200") {
          if (response.data["Data"]["data"].length > 0) {
            ss = '已缴费';
          } else {
            ss = '未缴费';
          }
        }
      });
    }
    return response.data;
  }

  // 返回每个隐藏的菜单项
  SelectView(String text, String id) {
    return PopupMenuItem<String>(
      value: id,
      child: Text(text),
    );
  }



  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  //确认工单提示框
  void showAlertGD() {

    //工单类型为热力维修必须上传确认图片
    if(assets.length==0&&detailEntity!.typeName!.contains('热力')) {
      Fluttertoast.showToast(msg: "请上传附件",gravity:ToastGravity.CENTER,fontSize: ScreenUtil().setSp(32));
      return;
    }

    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text("是否将选中工单进行确认？"),
            actions: <Widget>[
              new TextButton(
                  style: ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.black12)),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  style: ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.blueAccent)),
                  onPressed: () {
                    Navigator.pop(context);
                    if(_imageUrlsEdit.length==0) {
                      goCheckMenu();
                    }else{
                      submitImage();
                    }

                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
        });
  }

  void submitImage() async{

    //附件
    List fileList = [];

    if (mounted) {
      setState(() {
        isloading = false;
      });
    }

    for (int i = 0; i < assets.length; i++) {
      File? file = await assets[i].file;
      if (file != null) {
        var fileType = file.path.substring(file.path.lastIndexOf('.') + 1);
        if (fileType == 'jpg' || fileType == 'jpeg' || fileType == 'png') {
          //获得一个uuud码用于给图片命名
          final String uuid = Uuid().v1();
          final Directory _temp = await getTemporaryDirectory();
          final String _path = _temp.path;
          final result = await FlutterImageCompress.compressAndGetFile(
            file.absolute.path, '${_path}Image_$uuid.jpg',
            minWidth: 1080, //压缩后的最小宽度
            minHeight: 1920, //压缩后的最小高度
            quality: 20, //压缩质量
            rotate: 0, //旋转角度
          );

          fileList.add(result?.path);
        }
      } else {
        Fluttertoast.showToast(
          msg: '文件不存在',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );
      }
    }

    print('fileList=====$fileList');

    List formDataArr = [];
    for (int i = 0; i < fileList.length; i++) {
      var name = fileList[i]
          .substring(fileList[i].lastIndexOf("/") + 1, fileList[i].length)
          .toString()
          .replaceAll(" ", "");

      String imageBase64;
      EncodeUtil.image2Base64(fileList[i]).then((
          data) {
        imageBase64 = data; //data.replaceAll('+', "%2B");
        print("imageBase64===$imageBase64");

        var str = {
          "FileName": "$name",
          "Base64Str": "$imageBase64"
        };
        formDataArr.add(str);

        if (fileList.length == formDataArr.length) {
          uploadImageData(formDataArr);
        }
      });

    }
  }

  //上传图片
  Future uploadImageData(fileList) async {

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData= await AesUtil.encodeBase64();
    var data = {
      "key":key,
      "filedata":fileList,"ClientType":"phone","ClientKey":aesData
    };

    print("data===${fileList.length}${data.toString()}");
    print("data===${WebConfig().baseUrl + "Public/UploadFile"}");


    Response response = await Dio().post(WebConfig().baseUrl + "Public/UploadFile", data: data);

    print("response:${response.data}");

    if (response.data["Code"] == "200") {
      var result = response.data["Data"];

      print("上传附件返回result===$result");

      if(result.length>0){
        fileArrs.clear();
        for (int i = 0; i < result.length; i++) {
          fileArrs.add(result[i]);
        }

        goCheckMenu();
      }else {
        if (mounted) {
          setState(() {
            isloading = true;
          });
        }
        Fluttertoast.showToast(
          msg: "上传图片有误${response.data}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );
      }

    } else {
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      Fluttertoast.showToast(
        msg: response.data["Data"]["Msg"].toString(),
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,
      );
    }

    return response.data;

  }

  Future goCheckMenu() async {

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": widget.LSH,
      "fujian":fileArrs,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    Response response = await Dio().post(
        WebConfig().baseUrl + "Work/NiBuShiZhenZhengDeKuaiLe",
        data: data);
    print(response.data.toString());

    if (response.data["Code"] == "200") {
      Fluttertoast.showToast(msg: "操作成功");
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
    }
  }

  //退回工单
  void showAlertBack() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text("退回原因"),
            content: Container(
              height: ScreenUtil().setHeight(120),
              child: TextField(
                controller: ideaController,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(28),
                  //字母间距
                  letterSpacing: 0.5,
                  color: const Color(0xFF4A4A4A),
                ),
                decoration: InputDecoration(
                  hintStyle: TextStyle(
                      color: Colors.black54,
                      fontSize: ScreenUtil().setSp(28.0)),
                  hintText: "请输入退回原因",
                ),
              ),
            ),
            actions: <Widget>[
              new TextButton(
                  style: ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.black12)),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  style: ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.blueAccent)),
                  onPressed: () {
                    if (ideaController.text.toString().length > 0) {
                      if (detailEntity!.ifhb == 3) {
                        Fluttertoast.showToast(msg: "该工单已申请退回");
                        return;
                      }
                      Navigator.pop(context);
                      delay();
                    } else {
                      Fluttertoast.showToast(msg: '退回原因不能为空');
                    }
                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
        });
  }

  Future delay() async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": widget.LSH,
      "Reason": ideaController.text.toString(),
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio()
        .post(WebConfig().baseUrl + "Work/RequestHuanBan", data: data);
    if (mounted) {
      setState(() {
        isloading = true;
      });
    }
    if (response.data["Code"] == "200") {
      Fluttertoast.showToast(msg: "提交成功");
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
    }
  }

  //工单转交
  void showMyDialog() {
    //处理人员弹框
    showDialog(
        context: context,
        builder: (ctx) {
          return StatefulBuilder(
            builder: (context, state) {
              return SimpleDialog(
                title: Text("选择处理人员"),
                titlePadding: EdgeInsets.all(10),
                backgroundColor: Colors.white,
                elevation: 5,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(6))),
                children: <Widget>[
                  Container(
                    width: 200,
                    height: 300,
                    child: ListView.builder(
                      itemCount: personLists.length,
                      itemBuilder: (context, index) {
                        return Column(
                          children: <Widget>[
                            GestureDetector(
                              child: Container(
                                height: 50.0,
                                padding: EdgeInsets.only(left: 20.0),
                                width: 360.0,
                                child: Row(
                                  children: <Widget>[
                                    SizedBox(
                                      width: 10.0,
                                    ),
                                    Expanded(
                                        child: Text(
                                            "${personLists[index].realName}")),
                                  ],
                                ),
                              ),
                              onTap: () {
                                //取出点击的index
                                if (mounted) {
                                  setState(() {
                                    isloading = false;
                                  });
                                }

                                getPersonTongYiBuMen(personLists[index].iD)
                                    .then((data) {
                                  if (mounted) {
                                    setState(() {
                                      isloading = true;
                                    });
                                  }

                                  print(
                                      "data===$data=${personLists[index].iD}");
                                  if (data) {
                                    showDeliverConfirmDialog(
                                        personLists[index].realName,
                                        personLists[index].iD);
                                  }

                                  state(() {});
                                });

                                state(() {});
                              },
                            ),
                            Divider(),
                          ],
                        );
                      },
                    ),
                  )
                ],
              );
            },
          );
        });
  }

  //获取处理人员单选
  Future getPersonData() async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    personLists.clear();
    String aesData = await (AesUtil.encodeBase64());
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    var data = {
      "key": key,
      "Department_id": detailEntity!.departmentId,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio()
        .post(WebConfig().baseUrl + "Work/GetXiaFaRenYuan", data: data);
    personEntity = XiafaPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (personEntity.code == "200") {
      if (mounted) {
        setState(() {
          personEntity = XiafaPersonEntity.fromJson(response.data);
          personLists.addAll(personEntity.data!);
        });
      }
    }
    if (mounted) {
      setState(() {
        isloading = true;
      });
    }

    return response.data;
  }

  //判断选中处理人员是否属于同一部门
  Future getPersonTongYiBuMen(personID) async {
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "sdg": personID,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print("data===$data");
    Response response =
        await Dio().post(WebConfig().baseUrl + "DB/YanZhengBuMen", data: data);
    print(response.data.toString());
    if (response.data["Code"] == "200") {
      if (response.data["Data"] > 1) {
        Fluttertoast.showToast(msg: "请选择同一部门下的维修人员！");
        return false;
      } else {
        return true;
      }
    }
  }

  void showDeliverConfirmDialog(String? name, id) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("将工单转交给" + name!),
            content: Container(
              height: ScreenUtil().setHeight(120),
              child: TextField(
                controller: deliverController,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(28),
                  //字母间距
                  letterSpacing: 0.5,
                  color: const Color(0xFF4A4A4A),
                ),
                decoration: InputDecoration(
                  hintStyle: TextStyle(
                      color: Colors.black54,
                      fontSize: ScreenUtil().setSp(28.0)),
                  hintText: "请输入转交原因",
                ),
              ),
            ),
            actions: <Widget>[
              new TextButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                    goDeliver(id);
                  },
                  child: new Text(
                    "确定",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
              new TextButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                  },
                  child: new Text(
                    "取消",
                    style: TextStyle(fontSize: ScreenUtil().setSp(30)),
                  )),
            ],
          );
          ;
        });
  }

  Future goDeliver(ids) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "LSH": widget.LSH,
      "ClientType": "phone",
      "ClientKey": aesData,
      'ZF_User_id': ids,
      'Remark': deliverController.text.toString()
    };
    print(data.toString());

    Response response = await Dio().post(
        WebConfig().baseUrl + "Work/NiBuShiZhenZhengDeGaoXing",
        data: data);
    print(response.data.toString());

    if (response.data["Code"] == "200") {
      sendMessageGmAsync();
      Fluttertoast.showToast(msg: "操作成功");
      Navigator.pop(context);
      Navigator.pop(context);
    } else {
      Fluttertoast.showToast(msg: response.data["Msg"]);
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
    }
  }

  //转交工单成功后发送短信
  Future sendMessageGmAsync() async {

    print(WebConfig().sendMessageUrl+
        'Models/Handler2.ashx?method=SendMessageGmAsync&LSH='+detailEntity!.lSH!);

    Response response = await Dio().get(WebConfig().sendMessageUrl+
        'Models/Handler2.ashx?method=SendMessageGmAsync&LSH='+detailEntity!.lSH!,
    );
    print("发送短信: "+response.data.toString());


    return response.data;
  }
}
